package java_thinking.unit_11._11_12;

import java_thinking.TypeInfo.pets.Pet;
import java_thinking.TypeInfo.pets.Pets;

import java.util.AbstractCollection;
import java.util.Iterator;

/**
 * @Description :
 *      当你要实现一个不是Collection的外部类时,由于让它去实现Collection接口可能非常困难,因此使用Iterator就会变得非常吸引人
 *      ,实现Collection就必须实现iterator(),这里我们只要拿iterator()，实现Collection与继承AbstractCollection相比花费的代价略微大
 * @author: cww
 * @DateTime: 2019-03-18 23:38
 */

public class CollectionSequence extends AbstractCollection<Pet> {
    private Pet[] pets = Pets.createArray(8);
    /**
     * Returns an iterator over the elements contained in this collection.
     *
     * @return an iterator over the elements contained in this collection
     */
    @Override
    public Iterator<Pet> iterator() {
        return new Iterator<Pet>() {
            private int index = 0;
            @Override
            public void remove() {
                throw new UnsupportedOperationException("remove");
            }

            @Override
            public boolean hasNext() {
                return index<pets.length;
            }

            @Override
            public Pet next() {
                return pets[index++];
            }
        };
    }

    @Override
    public int size() {
        return pets.length;
    }

    public static void main(String[] args) {
        CollectionSequence sequence = new CollectionSequence();
        InterfaceVsIterator.display(sequence);
        InterfaceVsIterator.display(sequence.iterator());
    }
}
